package texture;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StitchSlot {
	private StitchHolder holder;
	private final int width;
	private final int height;
	private final int originX;
	private final int originY;
	private List<StitchSlot> subSlots;

	public StitchSlot(int par1, int par2, int par3, int par4) {
		this.originX = par1;
		this.originY = par2;
		this.width = par3;
		this.height = par4;
	}

	public boolean addSlot(StitchHolder stitchHolder) {
		if (this.holder != null) {
			return false;
		}

		int w = stitchHolder.getWidth();
		int h = stitchHolder.getHeight();

		if (w > this.width || h > this.height) {
			return false;
		}

		if (w == this.width && h == this.height) {
			this.holder = stitchHolder;
			return true;
		}

		if (this.subSlots == null) {
			this.subSlots = new ArrayList<>(1);
			this.subSlots.add(new StitchSlot(this.originX, this.originY, w, h));

			int k = this.width - w;
			int l = this.height - h;

			if (l > 0 && k > 0) {
				int i1 = Math.max(this.height, k);
				int j1 = Math.max(this.width, l);

				if (i1 >= j1) {
					this.subSlots.add(new StitchSlot(this.originX, this.originY + h, w, l));
					this.subSlots.add(new StitchSlot(this.originX + w, this.originY, k, this.height));
				} else {
					this.subSlots.add(new StitchSlot(this.originX + w, this.originY, k, h));
					this.subSlots.add(new StitchSlot(this.originX, this.originY + h, this.width, l));
				}
			} else if (k == 0) {
				this.subSlots.add(new StitchSlot(this.originX, this.originY + h, w, l));
			} else if (l == 0) {
				this.subSlots.add(new StitchSlot(this.originX + w, this.originY, k, h));
			}
		}

		Iterator<StitchSlot> iterator = this.subSlots.iterator();
		StitchSlot stitchslot;

		do {
			if (!iterator.hasNext()) {
				return false;
			}

			stitchslot = (StitchSlot) iterator.next();
		} while (!stitchslot.addSlot(stitchHolder));

		return true;
	}

	public void getAllStitchSlots(ArrayList<StitchSlot> par1List) {
		if (this.holder != null) {
			par1List.add(this);
		} else if (this.subSlots != null) {
			Iterator<StitchSlot> iterator = this.subSlots.iterator();

			while (iterator.hasNext()) {
				StitchSlot stitchslot = iterator.next();
				stitchslot.getAllStitchSlots(par1List);
			}
		}
	}

	public StitchHolder getStitchHolder() {
		return this.holder;
	}

	public int getOriginX() {
		return this.originX;
	}

	public int getOriginY() {
		return this.originY;
	}
}
